<template>
  <div class="app-container">
    <div class="container-box">
      <div class="table-title text-primary"> 活动记录</div>
      <div class="filter-container">
        <el-input v-model="listQuery.title" placeholder="查询内容" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />
        <el-select v-model="listQuery.type" placeholder="查询类型" clearable class="filter-item" style="width: 130px;margin-left: 10px;">
          <el-option v-for="item in calendarTypeOptions" :key="item.key" :label="item.display_name" :value="item.key" />
        </el-select>
        <el-select v-model="listQuery.status" placeholder="活动状态" clearable class="filter-item" style="width: 130px;margin-left: 10px;" @change="getList">
          <el-option v-for="item in calendarStatusOptions" :key="item.key" :label="item.display_name" :value="item.key" />
        </el-select>
        <el-button v-waves class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-search" @click="handleFilter">
          搜索
        </el-button>
        <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">
          添加活动记录
        </el-button>
        <el-button v-waves :loading="downloadLoading" class="filter-item" type="primary" icon="el-icon-download" @click="handleDownload">
          下载数据
        </el-button>
      </div>

      <el-table
        :key="tableKey"
        v-loading="listLoading"
        :data="list"
        fit
        highlight-current-row
        style="width: 100%;"
        @sort-change="sortChange"
      >
        <el-table-column label="#编号" prop="id" sortable="custom" align="center" width="70" :class-name="getSortClass('id')">
          <template slot-scope="{row}">
            <span>{{ row.id }}</span>
          </template>
        </el-table-column>
        <el-table-column label="活动名称" width="200px" align="center">
          <template slot-scope="{row}">
            <span style="overflow: hidden;text-overflow:ellipsis;white-space: nowrap;">{{ row.name }}</span>
          </template>
        </el-table-column>
        <el-table-column label="发起人" width="110px" align="center">
          <template slot-scope="{row}">
            <span>{{ row.hostname }}</span>
          </template>
        </el-table-column>
        <el-table-column label="发起社团" width="110px" align="center">
          <template slot-scope="{row}">
            <span>{{ row.hostOrg }}</span>
          </template>
        </el-table-column>
        <el-table-column label="举办场地" width="110px" align="center">
          <template slot-scope="{row}">
            <span>{{ row.need }}</span>
          </template>
        </el-table-column>
        <el-table-column label="预计规模" width="110px" align="center">
          <template slot-scope="{row}">
            <span>{{ row.scale }}</span>
          </template>
        </el-table-column>
        <el-table-column label="开放程度" width="150px" align="center">
          <template slot-scope="{row}">
            <span>{{ row.openScale }}</span>
          </template>
        </el-table-column>
        <el-table-column label="参与社团" min-width="110px" align="left">
          <template slot-scope="{row}">
            <span style="overflow: hidden;text-overflow:ellipsis;white-space: nowrap;">{{ row.participantOrgString }}</span>
          </template>
        </el-table-column>
        <el-table-column label="参与人" min-width="110px" align="left">
          <template slot-scope="{row}">
            <span style="overflow: hidden;text-overflow:ellipsis;white-space: nowrap;">{{ row.participantString }}</span>
          </template>
        </el-table-column>
        <el-table-column label="Status" class-name="status-col" width="100">
          <template slot-scope="{row}">
            <el-tag :type="row.status | statusFilter">
              {{ row.status }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="Actions" align="center" width="230" class-name="small-padding fixed-width">
          <template slot-scope="{row,$index}">
            <el-button type="primary" size="mini" @click="toDetail(row.id)">
              详情
            </el-button>
            <el-button size="mini" type="info" @click="handleUpdate(row,$index)">
              编辑
            </el-button>
            <el-button size="mini" type="danger" @click="handleDelete(row,$index)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="listQuery.total>0" :total="listQuery.total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />
    </div>

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="activity" :rules="rules" :model="temp" label-position="left" label-width="100px" style="width: 400px; margin-left:50px;">
        <el-form-item label="活动名称" prop="name">
          <el-input v-model="temp.name" />
        </el-form-item>
        <el-form-item label="发起人" prop="orgUser">
          <el-cascader v-model="temp.orgUser" :value="temp.orgUser" :options="orgMemberOptions" />
        </el-form-item>
        <el-form-item label="举办场所" prop="need">
          <el-input v-model="temp.need" />
        </el-form-item>
        <el-form-item label="活动时间" prop="dateSpan">
          <el-date-picker
            v-model="temp.dateSpan"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          />
        </el-form-item>
        <el-form-item label="参加社团" prop="participantOrg">
          <el-drag-select v-model="temp.participantOrg" style="width: 300px" multiple placeholder="请选择">
            <el-option v-for="item in orgOptions" :key="item.id" :label="item.name" :value="item.id" />
          </el-drag-select>
        </el-form-item>
        <el-form-item label="预计规模" prop="scale">
          <el-input v-model.number="temp.scale" placeholder="活动大致参与人数" />
        </el-form-item>
        <el-form-item label="开放程度" prop="openScale">
          <el-select v-model="temp.openScale" style="width: 300px" placeholder="请选择">
            <el-option v-for="item in openScaleOptions" :key="item.name" :label="item.name" :value="item.name" />
          </el-select>
        </el-form-item>
        <el-form-item v-if="dialogStatus === 'update' && this.$store.getters.isAdmin" label="状态" prop="status">
          <el-select v-model="temp.status" style="width: 300px" placeholder="请选择">
            <el-option v-for="item in calendarStatusOptions" :key="item.display_name" :label="item.display_name" :value="item.display_name" />
          </el-select>
        </el-form-item>
        <div class="text-danger">*参与者在详情处设置</div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData('activity'):createData('activity')">
          确定
        </el-button>
      </div>
    </el-dialog>
    <el-dialog title="删除确认" :visible.sync="deleteDialogFormVisible" style="width: 450px;margin: 0 auto">
      <div ref="dataForm" style="width: 100%;" class="text-danger">
        <span><i class="el-icon-warning-outline" /></span>
        删除数据将无法恢复
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button>
          取消
        </el-button>
        <el-button type="danger" @click="deleteData">
          确定
        </el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import ElDragSelect from '@/components/DragSelect'
import { fetchActivityList, addActivityBasic, deleteActivity } from '@/api/activity'
import { getOrgMemberOptions } from '@/api/user'
import { fetchOrgNames } from '@/api/com'
import { parseTime } from '@/utils'
import waves from '@/directive/waves' // waves directive
import Pagination from '@/components/Pagination' // secondary package based on el-pagination

const calendarTypeOptions = [
  { key: 'name', display_name: '发起人姓名' },
  { key: 'class', display_name: '班级' },
  { key: 'org', display_name: '社团' }
]
const calendarStatusOptions = [
  { key: '拒绝', display_name: '拒绝' },
  { key: null, display_name: '全选' },
  { key: '申请中', display_name: '申请中' },
  { key: '接受', display_name: '接受' }
]
const openScaleOptions = [
  { name: '社团内部开放' },
  { name: '校内开放' },
  { name: '对所有人开放' }
]
const calendarTypeKeyValue = calendarTypeOptions.reduce((acc, cur) => {
  acc[cur.key] = cur.display_name
  return acc
}, {})

export default {
  name: 'Activity',
  components: { Pagination, ElDragSelect },
  directives: { waves },
  filters: {
    statusFilter(status) {
      const statusMap = {
        '接受': 'success',
        '拒绝': 'danger',
        '申请中': 'info'
      }
      return statusMap[status]
    },
    typeFilter(type) {
      return calendarTypeKeyValue[type]
    }
  },
  data() {
    return {
      chart: null,
      tableKey: 0,
      list: null,
      listLoading: true,
      listQuery: {
        type: '',
        title: '',
        page: 1,
        limit: 10,
        total: 0,
        status: null
      },
      orgMemberOptions: null,
      calendarTypeOptions,
      calendarStatusOptions,
      openScaleOptions,
      orgOptions: [{
        value: '计算机服务队',
        label: '计算机服务队'
      }, {
        value: '软件俱乐部',
        label: '软件俱乐部'
      }, {
        value: '自行车协会',
        label: '自行车协会'
      }, {
        value: '红会',
        label: '红会'
      }, {
        value: '学生会',
        label: '学生会'
      }],
      showReviewer: false,
      temp: {
        id: null,
        name: null,
        hostUid: null,
        hostOrg: null,
        hostOid: null,
        hostname: null,
        scale: null,
        openScale: null,
        stDate: null,
        endDate: null,
        status: null,
        need: null,
        participant: [],
        participantOrg: [],
        orgUser: []
      },
      dialogFormVisible: false,
      deleteDialogFormVisible: false,
      deleteTemp: -1,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '新建'
      },
      dialogPvVisible: false,
      pvData: [],
      rules: {
        name: [
          { required: true, message: '请输入活动名称', trigger: 'change' },
          { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'change' }
        ],
        orgUser: [
          { required: true, message: '请选择活动发起人', trigger: 'change' }
        ],
        need: [
          { required: true, message: '请选择活动区域', trigger: 'change' }
        ],
        dateSpan: [
          { required: true, message: '请选择日期', trigger: 'change' }
        ],
        scale: [
          { required: true, message: '请输入活动规模', trigger: 'change', type: 'number' }
        ],
        openScale: [
          { required: true, message: '请选择活动开放程度', trigger: 'change' }
        ],
        participantOrg: [
          { required: true, message: '请选择活动参与的社团', trigger: 'change' }
        ]
      },
      downloadLoading: false,
      participantOrg: []
    }
  },
  created() {
    this.getList()
    getOrgMemberOptions().then(res => { this.orgMemberOptions = res.data.items })
    fetchOrgNames().then(res => { this.orgOptions = res.data.items })
  },
  methods: {
    changeOptions(event) {
      console.log(event)
    },
    getList() {
      this.listLoading = true
      fetchActivityList(this.listQuery).then(res => {
        console.log(res.data.items)
        const list = Object.assign([], res.data.items)
        this.listQuery.total = res.data.total
        this.list = []
        for (var i in list) {
          const formItem = {
            id: list[i].id,
            name: list[i].name,
            hostUid: list[i].hostUser.id,
            hostOrg: list[i].hostOrg.name,
            hostOid: list[i].hostOrg.id,
            hostname: list[i].hostUser.name,
            scale: list[i].scale,
            openScale: list[i].openScale,
            stDate: new Date(list[i].stDate).getTime(),
            endDate: new Date(list[i].endDate).getTime(),
            status: list[i].status,
            need: list[i].need
          }
          formItem['participant'] = []
          formItem['participantString'] = ''
          formItem['participantOrgString'] = ''
          formItem['participantOrg'] = []
          for (var j in list[i].users) {
            formItem.participantString += list[i].users[j].name + ', '
            formItem.participant.push(Number(list[i].users[j].id))
          }
          for (j in list[i].orgs) {
            formItem.participantOrgString += list[i].orgs[j].name + ', '
            formItem.participantOrg.push(Number(list[i].orgs[j].id))
          }
          formItem.participantString = formItem.participantString.substring(0, formItem.participantString.lastIndexOf(','))
          formItem.participantOrgString = formItem.participantOrgString.substring(0, formItem.participantOrgString.lastIndexOf(','))
          this.list.push(formItem)
        }
        console.log(this.list)
        setTimeout(() => {
          this.listLoading = false
        }, 1.5 * 1000)
      })
    },
    toDetail(id) {
      this.$router.push({ path: '/activity/detail/' + id })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    handleModifyStatus(row, status) {
      this.$message({
        message: '操作Success',
        type: 'success'
      })
      row.status = status
    },
    sortChange(data) {
      const { prop, order } = data
      if (prop === 'id') {
        this.sortByID(order)
      }
    },
    sortByID(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+id'
      } else {
        this.listQuery.sort = '-id'
      }
      this.handleFilter()
    },
    resetTemp() {
      this.temp = {
        id: null,
        name: null,
        hostUid: null,
        hostOrg: null,
        hostOid: null,
        hostname: null,
        scale: null,
        openScale: null,
        stDate: null,
        endDate: null,
        status: null,
        need: null,
        participant: [],
        participantOrg: [],
        orgUser: []
      }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
    },
    createData(formName) {
      console.log(formName)
      this.$refs[formName].validate((valid) => {
        if (valid) {
          const form = Object.assign({}, this.temp)
          form.stDate = parseTime(form.dateSpan[0], '{y}-{m}-{d} {h}:{i}:{s}')
          form.endDate = parseTime(form.dateSpan[1], '{y}-{m}-{d} {h}:{i}:{s}')
          form.hostOid = form.orgUser[0]
          form.hostUid = form.orgUser[1]
          form.status = this.dialogStatus === 'create' ? '申请中' : form.status
          console.log(form)
          addActivityBasic(form).then(
            res => {
              if (res.status === 200) {
                this.$notify({
                  title: 'Success',
                  message: 'Insert Successfully',
                  type: 'success',
                  duration: 2000
                })
                this.dialogFormVisible = false
                this.getList()
              }
            }
          )
        } else {
          return false
        }
      })
    },
    handleUpdate(row, index) {
      this.temp = Object.assign({}, this.list[index]) // copy obj
      console.log(this.temp)
      this.temp['dateSpan'] = []
      this.temp['orgUser'] = [Number(this.temp.hostOid), Number(this.temp.hostUid)]
      this.temp.dateSpan.push(this.temp.stDate)
      this.temp.dateSpan.push(this.temp.endDate)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
    },
    handleDelete(row, index) {
      this.temp = Object.assign({}, row)
      this.deleteDialogFormVisible = true
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          tempData.timestamp = +new Date(tempData.timestamp) // change Thu Nov 30 2017 16:41:05 GMT+0800 (CST) to 1512031311464
        }
      })
    },
    deleteData() {
      deleteActivity(this.temp).then(
        res => {
          if (res.status === 200) {
            this.$notify({
              title: 'Success',
              message: 'Delete Successfully',
              type: 'success',
              duration: 2000
            })
            this.getList()
          }
        }
      )
      this.deleteDialogFormVisible = false
    },
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['学号', '姓名', '性别', '社团', '职位', '状态', '简介']
        const filterVal = ['id', 'name', 'gender', 'org', 'position', 'status', 'intro']
        const data = this.formatJson(filterVal)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: '社团成员表（总）'
        })
        this.downloadLoading = false
      })
    },
    formatJson(filterVal) {
      return this.list.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    },
    getSortClass: function(key) {
      const sort = this.listQuery.sort
      return sort === `+${key}` ? 'ascending' : 'descending'
    }
  }
}
</script>
<style lang="scss" scoped>
  .container-box{
    margin: 20px;
    padding: 30px;
    border-radius: 5px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, .12), 0 0 6px rgba(0, 0, 0, .04);
  }
  .table-title{
    font-weight: bolder;
    font-size: 25px;
    margin-bottom: 20px;
  }
  .form-item{
    display: flex;
    flex-direction: row;
    font-size: 20px;
    margin: 5px;
  }
  .form-label{
    font-weight: bold;
  }
  .form-value{
    color: #7d7d7f;
  }
</style>
